<template>
	<div class="page-container">
		<el-card class="page-card w-full">
			<div class="flex justify-between w-full">
				<div class="w-[376px] mr-[32px]"></div>
				<el-card shadow="never" class="!border-none flex-1 goods__card" :body-style="{ padding: '0 !important' }">
					<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-width="90px" label-position="left">
						<el-form-item label="商品ID:" label-width="58px">
							<el-input v-model.trim="queryParams.id" clearable placeholder="请输入商品ID" />
						</el-form-item>
						<el-form-item label="商品名称:" label-width="75px">
							<el-input v-model.trim="queryParams.name" clearable placeholder="请输入商品名称" />
						</el-form-item>
						<el-form-item label="供应商名称:">
							<el-input v-model.trim="queryParams.userName" clearable placeholder="请输入供应商名称" />
						</el-form-item>
						<el-form-item>
							<div class="page-search-btn">
								<el-button icon="el-icon-search" type="primary" @click="handleQuery">搜索</el-button>
								<el-button icon="el-icon-refresh" type="primary" plain @click="resetQuery">重置</el-button>
							</div>
						</el-form-item>
					</el-form>
					<div class="page-card-options mt-[24px]">
						<el-button type="primary" icon="el-icon-plus" @click="handleAdd"> 发布商品 </el-button>
					</div>
					<el-table ref="goodsDown" v-loading="loading" :data="goodsList" stripe class="!w-full" @selection-change="handleSelectionChange">
						<el-table-column :formatter="emptyToString" align="center" label="序号" type="index" width="55" />
						<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="id"></el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="商品名称" prop="goods_name" show-overflow-tooltip width="150px">
							<template slot-scope="scope">
								<div class="goods-name-style">
									{{ scope.row.name }}
								</div>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="商品图片">
							<template slot-scope="scope">
								<el-image :preview-src-list="[scope.row.picUrl]" :src="scope.row.picUrl" style="width: 50px; height: 50px"></el-image>
							</template>
						</el-table-column>

						<el-table-column :formatter="emptyToNumber" align="center" label="商品价格">
							<template slot-scope="scope">
								<div>{{ scope.row.retailPrice || 0 }}</div>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="供应商名称" min-width="110" prop="userName" />
						<el-table-column :formatter="emptyToString" :width="tableAction" align="left" fixed="right" header-align="center" label="操作">
							<template slot-scope="scope">
								<div class="table-action">
									<el-button v-hasPermi="['mall:goods:edit']" type="primary" @click="handleUpdate(scope.row)">编辑 </el-button>
									<el-button v-hasPermi="['mall:goods:remove']" type="danger" @click="handleDelete(scope.row)">删除 </el-button>
								</div>
							</template>
						</el-table-column>
					</el-table>
					<pagination v-show="total > 0" :limit="queryParams.pageSize" :page="queryParams.pageNum" :total="total" @pagination="handleCurrentChange" />
				</el-card>
			</div>
		</el-card>
	</div>
</template>

<script>
import { addGoods, delGoods, exportGoods, getAuditGoods, listGoods, updateGoods, updateGoodsList } from '@/api/mall/goods';
import { listChild, listParent } from '@/api/mall/category';
import { isArray } from '@/utils/validate';
import tableMixins from '@/mixins/table';

export default {
	name: 'Goods',
	components: {},
	mixins: [tableMixins],
	data() {
		return {
			tableAction: 50,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			//待审核商品
			auditGoods: 0,
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 商品基本信息表格数据
			goodsList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				pageNum: this.$route.query.pageNum || 1,
				pageSize: 10,
				goodsSn: null,
				name: null,
				categoryId: null,
				brandId: null,
				gallery: null,
				keywords: null,
				brief: null,

				sortOrder: null,
				picUrl: null,
				shareUrl: null,
				isNew: null,
				isHot: null,
				unit: null,
				counterPrice: null,
				retailPrice: null,
				detail: null,
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				goodsSn: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
				name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
			},
			checkboxGroup: [],
			// 商品信息
			// 商品类型
			// 商品分类
			// 商品价格
			// 供应商价格
			// 销量
			// 商品库存
			// 商品状态
			// 创建时间
			cities: [
				{ value: true, label: '商品信息', id: 'a0' },
				{ value: true, label: '商品类型', id: 'a1' },
				{ value: true, label: '商品分类', id: 'a2' },
				{ value: true, label: '商品价格', id: 'a3' },
				{ value: true, label: '销量', id: 'a4' },
				{ value: true, label: '商品库存', id: 'a5' },
				{ value: true, label: '商品状态', id: 'a6' },
				{ value: true, label: '创建时间', id: 'a7' },
				{ value: true, label: '操作', id: 'a8' },
			],
			cobj: {
				a0: true,
				a1: true,
				a2: true,
				a3: true,
				a4: true,
				a5: true,
				a6: true,
				a7: true,
				a8: true,
			},
			goodsDetail: '',
			detailDialogVisible: false,
			goodsTypeList: [],
			props: {
				lazy: true,
				lazyLoad(node, resolve) {
					const { level, value } = node;
					if (level === 0) {
						listParent().then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: false,
							}));
							resolve(nodes);
						});
					} else {
						listChild(value).then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: true,
							}));
							resolve(nodes);
						});
					}
				},
			},
		};
	},

	created() {
		console.log(this.queryParams.pageNum);
		this.getList();
		this.getAuditList();
		this.getDicts('mall_goods_type').then((response) => {
			this.goodsTypeList = response.data;
		});
	},
	methods: {
		getAuditList() {
			getAuditGoods({
				current: 1,
				size: 10,
			}).then((res) => {
				this.auditGoods = res.data.total;
			});
		},
		goAudit() {
			this.$router.push({
				path: '/goods/audit',
			});
		},
		change(value) {
			for (let key in this.cobj) {
				console.log();
				if (value.indexOf(key) == -1) {
					this.$set(this.cobj, key, false);
				} else {
					this.$set(this.cobj, key, true);
				}
			}
		},
		/** 搜索商品基本信息列表 */
		editInventory(id) {
			this.$prompt('请输入需要编辑的库存数量', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^[0-9]\d*$)/,
				inputErrorMessage: '请输入正整数(包含0)',
			})
				.then(({ value }) => {
					updateGoods({ id, inventory: Number(value) }).then(() => {
						this.$message.success('编辑成功!');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		editPrice(id) {
			this.$prompt('请输入需要编辑的价格', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^\d+$)|(^\d+\.\d+$)/,
				inputErrorMessage: '请输入正数',
			})
				.then(({ value }) => {
					updateGoods({ id, retailPrice: Number(value) }).then(() => {
						this.$message.success('编辑成功!');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		getList() {
			this.loading = true;
			listGoods(this.queryParams)
				.then((response) => {
					this.goodsList = response.data.records;
					this.total = response.data.total;
					this.setActionWidth();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		handleCurrentChange(newPage) {
			this.queryParams.pageNum = newPage.page;
			this.queryParams.pageSize = newPage.limit;
			this.getList();
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				goodsSn: null,
				name: null,
				categoryId: null,
				brandId: null,
				gallery: null,
				keywords: null,
				brief: null,
				isOnSale: null,
				sortOrder: null,
				picUrl: null,
				shareUrl: null,
				isNew: null,
				isHot: null,
				unit: null,
				counterPrice: null,
				retailPrice: null,
				detail: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.queryParams = {
				pageNum: 1,
				pageSize: 10,
			};
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.$router.push('/goods/create');
		},
		/** 编辑按钮操作 */
		handleUpdate(row) {
			this.reset();
			console.log(this.queryParams.pageNum);
			const id = row.id || this.ids;
			this.$router.push('/goods/edit?id=' + id + '&pageNum=' + this.queryParams.pageNum);
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (this.form.id != null) {
						updateGoods(this.form).then((response) => {
							this.msgSuccess('编辑成功');
							this.open = false;
							this.getList();
						});
					} else {
						addGoods(this.form).then((response) => {
							this.msgSuccess('新增成功');
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			let ids = row.id || this.ids;
			if (!isArray(ids)) {
				ids = [ids];
			}

			this.$confirm('是否删除商品ID为"' + ids + '"的商品?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delGoods(ids);
				})
				.then(() => {
					this.getList();
					this.msgSuccess('删除成功');
				});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有商品基本信息数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return exportGoods(queryParams);
				})
				.then((response) => {
					this.download(response.msg);
				});
		},
		showDetail(detail) {
			this.goodsDetail = detail;
			this.detailDialogVisible = true;
		},
		handleUpdateStatus(row) {
			updateGoods({ id: row.id, isOnSale: row.isOnSale })
				.then(() => {
					this.$message.success(row.isOnSale ? '上架成功' : '下架成功');
					this.getList();
				})
				.catch((err) => {
					row.status = !row.status;
				});
		},
		handleCategoryChange(value) {
			this.queryParams.categoryId = value[value.length - 1];
		},
		batchPutAway(row) {
			let currentSelect = this.$refs.goodsDown.selection;
			let itemArr = [];

			for (let i = 0; i < currentSelect.length; i++) {
				itemArr.push(currentSelect[i]);
				currentSelect[i].isOnSale = 1;
				console.log(currentSelect[i]);
			}
			updateGoodsList(itemArr).then((res) => {
				this.$message.success('上架成功!');
				this.getGoodsList();
			});
		},
		batchSoldOut(row) {
			let currentSelect = this.$refs.goodsDown.selection;
			let itemArr = [];

			for (let i = 0; i < currentSelect.length; i++) {
				itemArr.push(currentSelect[i]);
				currentSelect[i].isOnSale = 2;
				console.log(currentSelect[i]);
			}
			updateGoodsList(itemArr).then((res) => {
				this.$message.success('下架成功!');
				this.getGoodsList();
			});
		},
	},
};
</script>
<style>
.minibtn_padding.el-button--primary {
	background-color: #1d2eb8;
	border-color: #1d2eb8;
}

.minibtn_padding.el-button--danger {
	background-color: #1a2483;
	border-color: #1a2483;
}
</style>
<style lang="scss" scoped>
.goods__card {
	::v-deep .el-card__header {
		padding: 0 !important;
	}
}
.btn-box {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.right {
		width: 321px;
		height: 36px;
		background: #eff0ff;
		border: 1px solid #c9d0ff;
		opacity: 1;
		border-radius: 5px;
		font-size: 12px;
		padding-left: 16px;
		box-sizing: border-box;
		line-height: 36px;
		cursor: pointer;
	}
}
</style>
